package com.easygem.controller.front;

import com.easygem.common.annotation.ControllerEndpoint;
import com.easygem.common.model.front.*;
import com.easygem.common.response.ResponseBean;
import com.easygem.common.response.ResponseMessage;
import com.easygem.common.utils.ExcelUtils;
import com.easygem.common.vo.front.ResourceInfoVO;
import com.easygem.common.vo.system.PageVO;
import com.easygem.front.service.*;
import com.wuwenze.poi.ExcelKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 肖智
 * @version 1.0
 * @Description 客户控制层
 * @date 2024/12/25
 */
@Api(tags = "客户")
@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;
    @Autowired
    private IndustryService industryService;
    @Autowired
    private FrontClientTypeService clientTypeService;
    @Autowired
    private CustomerFollowService customerFollowService;
    @Autowired
    private SourceService sourceService;
    @Autowired
    private ClientStatusService clientStatusService;
    @Autowired
    private LabelInfoService labelInfoService;
    @Autowired
    private BlackListService blackListService;
    @Autowired
    private ResourceInfoService resourceInfoService;

    //模糊查询客户
    @ApiOperation(value = "客户列表", notes = "模糊查询客户列表")
    @GetMapping("/findList")
    @ResponseBody
    public ResponseBean<PageVO<ResourceInfo>> getCustomerList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                              @RequestParam(value = "pageSize", defaultValue = "7") Integer pageSize,
                                                              ResourceInfoVO resourceInfoVO) {
        PageVO<ResourceInfo> resourceInfoList = customerService.findCustomerList(pageNum, pageSize, resourceInfoVO);
        return ResponseBean.success(resourceInfoList);
    }

    //客户详情
    @ApiOperation(value = "客户详情", notes = "根据id查询客户详情")
    @GetMapping("/getClientById")
    @ResponseBody
    public ResponseMessage<ResourceInfo> getClientById(@RequestParam(value = "resourceId") Long resourceId) {
        ResourceInfo resourceInfo = customerService.getCustomerById(resourceId);
        System.out.println("客户详细信息对象" + resourceInfo);
        return ResponseMessage.success(resourceInfo);
    }

    //客户修改
    @ApiOperation(value = "客户修改", notes = "根据客户ID修改客户信息")
    @PutMapping("/editCustomerById")
    @RequiresPermissions({"customer:edit"})
    @ResponseBody
    public ResponseBean<Integer> editCustomerById(@RequestBody ResourceInfo resourceInfo) {
        System.out.println("修改参数：" + resourceInfo);
        ResourceInfo r = customerService.getCustomerById(resourceInfo.getResourceId());
        if (r.getPhoneA().equals(resourceInfo.getPhoneA())) {
            resourceInfo.setPhoneA(null);
        }
        if (r.getPhoneB() != null && resourceInfo.getPhoneB() != null && r.getPhoneB().equals(resourceInfo.getPhoneB())) {
            resourceInfo.setPhoneB(null);
        }
        Integer isExistPhone = customerService.isExistPhone(resourceInfo.getPhoneA(), resourceInfo.getPhoneB(),resourceInfo.getAccountName());
        if (isExistPhone <= 0) {
            resourceInfo.setEditTime(Timestamp.from(Instant.now()).toString());
            //调用服务层的编辑方法，传递修改的客户信息
            Integer result = customerService.editCustomerById(resourceInfo);
            return ResponseBean.success(result);
        }
        return ResponseBean.success(-1);
    }

    //添加标签
    @ApiOperation(value = "添加客户标签", notes = "根据客户ID添加客户标签")
    @PutMapping("/addCustomerLabel")
    @ResponseBody
    public ResponseBean<Integer> addCustomerLabel(@RequestBody Map<String, Object> requestMap) {
        // 从 Map 中获取 resourceId 和 labelId
        Long resourceId = Long.valueOf(requestMap.get("resourceId").toString());
        Integer labelId = Integer.valueOf(requestMap.get("labelId").toString());
        // 调用服务层的添加方法
        Integer result = customerService.addCustomerLabel(resourceId, labelId);
        return ResponseBean.success(result);
    }

    //删除客户
    @ApiOperation(value = "删除客户", notes = "根据客户ID删除客户")
    @PutMapping("/deleteCustomerById")
    @RequiresPermissions({"customer:updateIsDelete"})
    @ResponseBody
    public ResponseBean<Integer> deleteCustomerById(@RequestBody Map<String, Long[]> request) {
        Long[] resourceIds = request.get("resourceIds");
        System.out.println("删除的客户id: " + Arrays.toString(resourceIds));
        Integer result = customerService.deleteCustomerById(resourceIds, Timestamp.from(Instant.now()).toString());
        return ResponseBean.success(result);
    }

    //加入黑名单
    @ApiOperation(value = "加入黑名单", notes = "加入黑名单")
    @PostMapping("/addBlackList")
    @RequiresPermissions({"customer:addBlackList"})
    @ResponseBody
    public ResponseBean<Integer> addBlackList(@RequestBody Map<String, String> request,@RequestParam("accountName") String accountName) {
        String clientName = request.get("clientName");
        String clientPhone = request.get("clientPhone");
        String clientPhoneB = request.get("clientPhoneB");
        String remark = request.get("remark");
        Long userId = customerService.getAdminIdByAccountName(accountName);
        String createTime = Timestamp.from(Instant.now()).toString();
        Blacklist blacklist = new Blacklist();
        blacklist.setClientName(clientName);
        blacklist.setClientPhone(clientPhone);
        blacklist.setRemark(remark);
        blacklist.setUserId(userId);
        blacklist.setCreateTime(createTime);
        Integer result = 0;
        result += blackListService.addBlackList(blacklist);
        if (clientPhoneB != null && !clientPhoneB.isEmpty()) {
            blacklist.setClientPhone(clientPhoneB);
            result += blackListService.addBlackList(blacklist);
        }
        return ResponseBean.success(result);
    }

    //添加客户
    @ApiOperation(value = "添加客户", notes = "添加客户")
    @RequiresPermissions({"customer:add"})
    @PostMapping("/addCustomer")
    @ResponseBody
    public ResponseBean<Integer> addCustomer(@RequestBody ResourceInfo resourceInfo,@RequestParam String accountName) {
        Integer isExistPhone = customerService.isExistPhone(resourceInfo.getPhoneA(), resourceInfo.getPhoneB(),accountName);
        if (isExistPhone <= 0) {
            String createTime = Timestamp.from(Instant.now()).toString();
            Long userId = customerService.getAdminIdByAccountName(accountName);
            resourceInfo.setUserId(userId);
            resourceInfo.setAccountName(accountName);
            resourceInfo.setCreateTime(createTime);
            resourceInfo.setResourceTag(3);
            resourceInfo.setIsExists(1);
            resourceInfo.setIsHighSeas(0);
            Integer result = customerService.addCustomer(resourceInfo);
            return ResponseBean.success(result);
        }
        return ResponseBean.success(-1);
    }


    //添加客户跟进
    @ApiOperation(value = "添加客户跟进", notes = "添加客户跟进")
    @PostMapping("/addCustomerFollow")
    @ResponseBody
    public ResponseBean<Integer> addCustomerFollow(@RequestBody CustomerFollow customerFollow ,@RequestParam String accountName) {
        Long adminId = customerService.getAdminIdByAccountName(accountName);
        String followTime = Timestamp.from(Instant.now()).toString();
        customerFollow.setUserId(adminId);
        customerFollow.setFollowTime(followTime);
        Integer result = customerFollowService.addCustomerFollow(customerFollow);
        return ResponseBean.success(result);
    }


    //跟进详情
    @ApiOperation(value = "跟进详情", notes = "根据客户编号获取跟进详情")
    @GetMapping("/getCustomerFollowByClientId")
    @ResponseBody
    public ResponseMessage<List<CustomerFollow>> getCustomerFollowByClientId(@RequestParam(value = "resourceId") Long resourceId) {
        List<CustomerFollow> customerFollowList = customerFollowService.getCustomerFollowListByClientId(resourceId);
        return ResponseMessage.success(customerFollowList);
    }


    //行业类型列表
    @ApiOperation(value = "行业类型列表", notes = "查询所有行业类型")
    @GetMapping("/findIndustryVOList")
    @ResponseBody
    public List<Industry> findIndustryVOList(@RequestParam("accountName") String accountName) {
        System.out.println("1111111账户名："+accountName);
        return industryService.findIndustryList(accountName);
    }

    //客户种类列表
    @ApiOperation(value = "客户种类列表", notes = "查询所有客户种类")
    @GetMapping("/findClientTypeVOList")
    @ResponseBody
    public List<ClientType> findClientTypeVOList(@RequestParam("accountName") String accountName) {
        return clientTypeService.findClienttypeList(accountName);
    }

    //客户来源列表
    @ApiOperation(value = "客户来源列表", notes = "客户来源列表")
    @GetMapping("/findSourceVOList")
    @ResponseBody
    public List<Source> findSourceVOList(@RequestParam("accountName") String accountName) {
        return sourceService.selectSource(accountName);
    }

    //标签列表
    @ApiOperation(value = "标签列表", notes = "标签列表")
    @GetMapping("/findLabelInfoVOList")
    @ResponseBody
    public List<LabelInfo> findLabelInfoVOList(@RequestParam("accountName") String accountName) {
        return labelInfoService.findLabelInfoList(accountName);
    }

    //客户状态列表
    @ApiOperation(value = "客户状态列表", notes = "客户状态列表")
    @GetMapping("/findClientStatusVOList")
    @ResponseBody
    public List<ClientStatus> findClientStatusVOList(@RequestParam("accountName") String accountName) {
        return clientStatusService.selectClientStatus(accountName);
    }

    //批量导出excel
    @ApiOperation(value = "批量导出excel", notes = "根据传入的id列表批量导出用户的excel表格")
    @PostMapping("/excelBatch")
    @RequiresPermissions("user:export")
    @ControllerEndpoint(exceptionMessage = "批量导出Excel失败", operation = "批量导出用户excel")
    public void batchExport(HttpServletResponse response,
                            @RequestBody List<Long> ids) {
        List<ResourceInfo> resourceInfoList = customerService.findAllByIds(ids);
        ExcelKit.$Export(ResourceInfo.class, response).downXlsx(resourceInfoList, false);
    }

    //批量导入
    @PostMapping("/importClient")
    @ResponseBody
    @ControllerEndpoint(exceptionMessage = "导入客户失败", operation = "导入客户")
    public ResponseMessage importResource(@RequestParam("file") MultipartFile file,@RequestParam("accountName") String accountName) throws Exception {
        //创建表格规则
        Map<String, String> map = new HashMap<>();
        map.put("客户名称", "resourceName");
        map.put("联系人", "linkman");
        map.put("电话A", "phoneA");
        map.put("电话B", "phoneB");
        map.put("备注", "remark");
        //解析表格
        List<ResourceInfo> resourceInfoListExcel = ExcelUtils.parseExcel(file, ResourceInfo.class, map);
        //去重号码
        List<ResourceInfo> resourceInfoList =ExcelUtils.deWeightResourceInfo(resourceInfoListExcel);
        //调用导入资源方法
        customerService.importClient(resourceInfoList,accountName);
        return ResponseMessage.success("success");
    }
}
